﻿using System.IO;
using System.Resources;

namespace CommonUtils
{
    /// <summary>
    /// 资源读取
    /// </summary>
    public static class ResourceUtil
    {
        public static Stream Get(string path)
        {
            var type = ReflectionUtil.GetClassType(2);
            ConsoleUtil.WriteLine("ResourceUtil.Get type: " + type.FullName);
            path = type.GetAssemblyName().Append(".", path);
            ConsoleUtil.WriteLine("ResourceUtil.Get path: " + path);
            return type.Assembly.GetManifestResourceStream(path);
        }

        /// <summary>
        /// 获取公用类库嵌入的资源
        /// </summary>
        public static Stream GetFromCommon(ResourceName resourceName)
        {
            string name = "";

            switch (resourceName)
            {
                case ResourceName.LoadingGif:
                    name = "loading.gif";
                    break;
                case ResourceName.MissingJpg:
                    name = "missing.jpg";
                    break;
                case ResourceName.MissingPng:
                    name = "missing.png";
                    break;
                case ResourceName.MissingMinJpg:
                    name = "missing-min.jpg";
                    break;
                case ResourceName.SqliteDb:
                    name = "sqlite.db";
                    break;
                case ResourceName.TestTxt:
                    name = "test.txt";
                    break;
                case ResourceName.IpDivisionTxt:
                    name = "ip-division.txt";
                    break;
            }

            var path = ReflectionUtil.CommonAssemblyName.Append(".Resources.", name);
            var stream = ReflectionUtil.CommonAssembly.GetManifestResourceStream(path);
            if (stream == null)
                throw new ExceptionPlus("读取资源文件失败：" + path);
            return stream;
        }

        /// <summary>
        /// 生成读取器
        /// </summary>
        public static ResourceReader GetReader(Stream stream)
        => new ResourceReader(stream);

        /// <summary>
        /// 获取读取器数据
        /// </summary>
        public static byte[] ReadBytes(this ResourceReader reader, string path)
        {
            reader.GetResourceData(path, out _, out byte[] data);
            return data;
        }
    }
}
